import mqtt, {
	connect,
	log
} from 'mqtt/dist/mqtt.js'
var client
class mqttUtil {
	constructor({
		ip = '10.180.15.196:8083/mqtt'
	} = {}) {
		this.mqtt_ip = ip
		this.mqtt_options = {
			connectTimeout: 5000,
			clientId: "IVIZTaskX1221bbnnvn1",
			username: 'emqx',
			password: 'public',
			clean: false
		}
		this.topic = ["android2can","zhonghui"];

	}
	connect() {
		var that = this
		var hosts = ''
		// #ifdef H5
		hosts = 'ws://' + this.mqtt_ip
		// #endif
		// #ifdef MP-WEIXIN||APP-PLUS
		hosts = 'wx://' + this.mqtt_ip
		// #endif
		if (client == null || client.connected == false) {
			client = mqtt.connect(hosts, this.mqtt_options)
			console.log("连接成功", this.mqtt_options)
			client.on('connect', function() {
				client.subscribe(that.topic, function(err) {
					if (!err) {
						console.log("订阅成功")
					}
				})
			})
			client.on('message', function(topic, message) {
				console.log(topic);
				console.log(message.toString());
				let msgArr = message.toString().split(',')
				uni.$emit(`data_${topic}`, {
					msg: message.toString()
				})
				console.log("收", message.toString());
			})
		}
		client.on('reconnect', function(error) {
			uni.showToast({
				title: '正在重连',
				icon: 'none'
			})
		})
		client.on('error', function(error) {
			uni.showToast({
				title: '连接失败.....',
				icon: 'none'
			})
		})
		client.on('end', function() {
			uni.showToast({
				title: '连接断开....',
				icon: 'none'
			})
		})

	}
	sendMes(topic = 'android2can', msg) {
		console.log(topic, msg);
		client.publish(topic, msg)
		console.log(msg);
	}
	get(callback) {
		client.on('message', callback);

	}
	unsubscribe() {
		var that = this
		client.unsubscribe(that.topic, err => {
			uni.showToast({
				title: '取消订阅成功',
				icon: 'none'
			})
		});
	}
	unconnect() {
		if (!client || client.connect) {
			uni.showToast({
				title: '未连接',
				icon: 'none'
			})
			return;

		}
		client.end();
		client = null
		uni.showToast({
			title: '断开连接',
			icon: 'none'
		})
	}
}
export default mqttUtil